<?php

declare(strict_types=1);
/**
 * Author: Zane
 * Email: 873934580@qq.com
 * Date: 2023/5/30.
 */

namespace App\Http\Controllers\System;

use App\Enum\StatusEnum;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Traits\EditTrait;
use App\Http\Controllers\Traits\ExtendTrait;
use App\Http\Controllers\Traits\ValidateTrait;
use App\Models\Configure;
use App\Models\ConfigureCate;
use App\Utils\ResultsVo;
use Illuminate\Validation\Rule;

class ConfigureController extends Controller
{
    use EditTrait;
    use ExtendTrait;
    use ValidateTrait;

    public function index(): \Illuminate\Http\JsonResponse
    {
        $results = Configure::query()->where('configure_cate_id', 0)->get();

        return ResultsVo::success($results);
    }

    public function store(): \Illuminate\Http\JsonResponse
    {
        $allow = [
            'status', 'title', 'logo', 'url', 'seo_title', 'seo_keyword', 'seo_description', 'copyright', 'filing_number',
            'police_filing_number',
        ];
        $data = request()->all($allow);
        foreach ($data as $key => $item) {
            Configure::query()
                ->updateOrInsert([
                    'name' => $key,
                    'configure_cate_id' => 0,
                ], [
                    'title' => '',
                    'name' => $key,
                    'value' => $item,
                    'type' => 'input',
                ])
            ;
        }

        return ResultsVo::success();
    }

    public function rules(): array
    {
        $id = (int) request()->route('id');
        $configureCateId = (int) request()->get('configure_cate_id');

        return [
            'title' => ['required', 'max:255',
                Rule::unique(Configure::class)->where(function ($query) use ($configureCateId): void {
                    $query->where('configure_cate_id', $configureCateId);
                })->ignore($id),
            ],
            'name' => ['required', 'max:255',
                Rule::unique(Configure::class)->where(function ($query) use ($configureCateId): void {
                    $query->where('configure_cate_id', $configureCateId);
                })->ignore($id),
            ],
            'configure_cate_id' => ['required', 'integer',
                Rule::exists(ConfigureCate::class, 'id')
                    ->where(function ($query): void {
                        $query->where('status', StatusEnum::ENABLE);
                    }),
            ],
            'weight' => 'integer|min:0|max:255',
            'remark' => 'max:255',
        ];
    }
}
